import defaultSettings from '@/settings'

const { sideTheme, dynamicTitle } = defaultSettings

const storageSetting = JSON.parse(localStorage.getItem('layout-setting')) || ''
const state = {
  title: '',
  theme: storageSetting.theme || '#4B6EEF',
  sideTheme: sessionStorage.getItem('_THEME') || storageSetting.sideTheme || sideTheme,
  keepAlivePage: [],
  dynamicTitle: storageSetting.dynamicTitle === undefined ? dynamicTitle : storageSetting.dynamicTitle

}
const mutations = {
  CHANGE_SETTING: (state, { key, value }) => {
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  },
  WATCH_SETTING: (state, data) => {
    for (const key in data) {
      if (state.hasOwnProperty(key)) {
        state[key] = data[key]
      }
    }
  },
  ADD_KEEP_ALVE: (state, name) => {
    const index = state.keepAlivePage.indexOf(name)
    if (index == -1) {
      state.keepAlivePage = state.keepAlivePage.concat(name)
    }
  },
  CHANGE_KEEP_ALIVE: (state, name) => {
    const keepAlivePage = state.keepAlivePage
    const index = keepAlivePage.indexOf(name)
    if (index > -1) {
      keepAlivePage.splice(index, 1)
    }
  },
  CLEAR_KEEP_ALIVE: (state) => {
    state.keepAlivePage = []
  }

}

const actions = {
  // 修改布局设置
  changeSetting({ commit }, data) {
    commit('CHANGE_SETTING', data)
  },
  // 添加缓存
  addKeepAlivePage({ commit }, name) {
    commit('ADD_KEEP_ALVE', name)
  },
  // 去掉缓存
  changeKeepAlive({ commit }, name) {
    commit('CHANGE_KEEP_ALIVE', name)
  },
  // 清空缓存
  clearKeepAlive({ commit }) {
    commit('CLEAR_KEEP_ALIVE')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
